<?php
/**
 * Created by PhpStorm.
 * User: PHP
 * Date: 2021/6/7
 * Time: 17:31
 */
namespace App\Dao\notice;
use App\Dao\BaseDao;
use App\Models\notice\NoticeModel;
use Illuminate\Support\Facades\DB;
use App\Dao\system\SystemRoleDao;
use App\Dao\system\SystemAdminDao;
use App\Exceptions\ApiException as HOException;
use App\Dao\notice\NoticeRecordDao;
/**
 *  公告管理
 * */
class NoticeDao extends BaseDao
{

    public function setModel(){
        return NoticeModel::class;
    }


    //公告列表
    public function NoticeList($where){

        $search = [];
        if($where['title']){
            $search[] = ['title', 'like', '%' . $where['title'] . '%'];
        }

        if ($where['created_at']){
            $search[] = ['created_at','=',$where['created_at']];
        }

        $return_list = $this->models::where($search)->orderBy('id','desc')->paginate($where['limit']);

        $res = $this->formatData($return_list);

        foreach ($res['data'] as $k=>&$v){
            $v['un_name'] = DB::table('un_store')->where('id',$v['store_id'])->value('un_name');
        }
        return $res;

    }





    //登录显示公告
    public function  red_notice($userId){
        $systemAdminServices = app()->make(SystemAdminDao::class);

        $role_id= $systemAdminServices->get_roleId($userId);

        if ($role_id == 3){
            return $this->models::where('user_type','<>',2)->where('hide',0)->where('is_read',0)->select('id','title','synopsis','created_at')->get();
        }

        if ($role_id == 2){
            return $this->models::where('user_type','<>',1)->where('hide',0)->where('is_read',0)->select('id','title','synopsis','created_at')->get();
        }


    }



    //已读公告
    public function read($data){

        DB::beginTransaction();
        try{
            $quantity_seen  = $this->models::where(['id'=>$data['notice_id']])->value('quantity_seen');

            $this->update(['id'=>$data['notice_id']],['is_read'=>1,'quantity_seen'=>$quantity_seen+1]);

            $NoticeRecordDao = app()->make(NoticeRecordDao::class);

            $NoticeRecordDao->add_record($data);

            DB::commit();
            return true;
        } catch(\Exception $exception) {
            DB::rollBack();
            throw new HOException($exception->getMessage());

        }

    }


    //已读公告人数
    public function read_person($notice_id){
        $NoticeRecordDao = app()->make(NoticeRecordDao::class);
        return $NoticeRecordDao->get_list($notice_id);
    }




}
